#!/usr/bin/env python
# Create: 2018/11/7
__author__ = '749B'

import re
import requests

from sds.swis_login import swis


def add_node(ip_addr, node_name, engine_id=13, object_sub_type='ICMP'):
    props = {
        'IPAddress': ip_addr,
        'NodeName': node_name,
        'EngineID': engine_id,
        'ObjectSubType': object_sub_type,
    }
    print("\r{} {} 添加节点... ".format(props['IPAddress'], props['NodeName']), end="")
    uri = swis.create('Orion.Nodes', **props)
    if not uri:
        print("ERROR!")
    print("DONE!", end='\t')
    return uri


def add_pollers(nodeid, ip_addr, node_name):
    pollers_enabled = {
        'N.Status.ICMP.Native': True,
        'N.ResponseTime.ICMP.Native': True,
    }
    pollers = []
    for k in pollers_enabled:
        pollers.append(
            {
                'PollerType': k,
                'NetObject': 'N:' + nodeid,
                'NetObjectType': 'N',
                'NetObjectID': nodeid,
                'Enabled': pollers_enabled[k]
            }
        )
    for poller in pollers:
        print("\r{} {} Adding poller type: {} with status {}... ".format(
            ip_addr, node_name, poller['PollerType'], poller['Enabled']), end="")
        response = swis.create('Orion.Pollers', **poller)
        print("DONE!", end='\t')


def update_custom_property(uri, ip_addr, node_name, **kwargs):
    print("\r{} {} update {} ... ".format(ip_addr, node_name, kwargs), end="")
    resp = swis.update(uri + '/CustomProperties', **kwargs)
    # obj = swis.read(uri + '/CustomProperties')
    # print(obj)
    if resp:
        print("Update返回异常:", resp)
    return resp


def run(ip_addr, node_name, custom_property=None):
    uri = add_node(ip_addr, node_name)
    if not uri:
        return
    nodeid = re.search(r'(\d+)$', uri).group(0)
    if not nodeid:
        print("没有获取到nodeid!")
    add_pollers(nodeid, ip_addr, node_name)
    if custom_property:
        resp = update_custom_property(uri, ip_addr, node_name, **custom_property)
        return resp


requests.packages.urllib3.disable_warnings()


if __name__ == '__main__':
    #custom_property = {'Department': "IDX金桥DC", 'City': "视频监控_海康"}
    custom_property = {'City': "TEST1"}
    run('114.114.114.114', "DNS_114_TEST", custom_property)
    print("\n完成")
